﻿namespace DesignModeConsole.结构型.组合模式;

internal class FileSystemMode
{
    private List<FileSystemMode> SubNodes = new List<FileSystemMode>();

    public FileSystemMode(string path, bool isFile)
    {
        Path = path;
        IsFile = isFile;
    }

    public string Path { get; set; }

    public bool IsFile { get; set; }

    /// <summary>
    /// 获取文件数量
    /// </summary>
    /// <returns></returns>
    public int CountNumOfFiles()
    {
        if (IsFile)
            return 1;

        var numOfFile = 0;
        foreach (var item in SubNodes)
        {
            numOfFile += item.CountNumOfFiles();
        }
        return numOfFile;
    }

    /// <summary>
    /// 获取文件大小
    /// </summary>
    /// <returns></returns>
    public long CountSizeOfFiles()
    {
        if (IsFile)
        {
            var exist = File.Exists(Path);
            if (!exist)
            {
                return 0;
            }
            return File.ReadAllBytes(Path).Length;
        }

        long sizeOfFile = 0;
        foreach (var item in SubNodes)
        {
            sizeOfFile += item.CountSizeOfFiles();
        }
        return sizeOfFile;
    }

    public void AddSubNode(FileSystemMode fileSystem)
    {
        SubNodes.Add(fileSystem);
    }

    public void RemoveSubNode(FileSystemMode fileSystem)
    {
        SubNodes.Remove(fileSystem);
    }
}